<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;
class GoodsController extends Controller
{
    public function index(Request $request)
    {
    	$where = [];
    	//实例化要操作的表
    	$db = DB::table('goods');
		$db->join('cates','cates.id','=','goods.cate_id')
    	->select('goods.*','cates.name')->get();
    	//判断有没有搜索title字段的值
    	if($request->has('title')){
    		// 获取要搜索的title字段的值
    		$title = $request->input('title');
    		//添加where模糊匹配条件
    		$db->where('title','like',"%{$title}%");
    		$where['title'] = $title;
    	}
    	// dd($db);
    	// 分页
    	$list = $db->paginate(3);
    	//加载模板
    	return view('admin.good.index',['list'=>$list,'where'=>$where]);
    }

    public function create()
    {
    	return view('admin.good.add');
    }

    public function store(Request $request)
    {
    	// dd($request);
    	$data = $request->except('_token'); 
        if ($request->hasFile('showImg')) {
            if ($request->file('showImg')->isValid()) {
                $file = $request->file('showImg');
                // dd($file);
                $ext = $file->getClientOriginalExtension();
                // dd($ext);
                $showImg = time().rand(1000,9999).'.'.$ext;
                $file->move('./uploads/',$showImg);
                if($file->getError()>0){ 
                    echo '上传失败';
                }else{
                    echo '上传成功';
                }
            }
        }else{
            echo "<script>alert('请选择图片');</script>";
            return redirect('admin/goods/create');
        }    
        $data['showImg'] = $showImg;        
        $row = DB::table('goods')->insertGetId($data);        
        if($row>0){
            return redirect('admin/goods');
    
        }
    	
    }

    public function destroy($id)
    {
    	$row = DB::table('goods')->where('id',$id)->delete();

    	if($row>0){
    		return redirect('admin/goods');
    	}
    }

    public function edit($id)
    {
    	$list = DB::table('goods')->where('id',$id)->first();
         // dd($list);
    	return view('admin.good.edit',['list'=>$list]);
    }

    public function update($id,Request $request)
    {

        $data = $request->except('_token','_method');
        $list = DB::table('goods')->where('id',$id)->update($data);
        // dd($list);
        if($list>0){
            return redirect('admin/goods');
        }else{
            return back()->with('msg','修改失败');
        }
    }
}
    	